import React from "react";
import { Formik } from "formik";
import styles from "./PlayerInput.less";

export function PlayerInput(props) {
  const { title, playerInfo, onClearInput, onSubmitPlayer } = props;
  const name = playerInfo?.name ?? playerInfo?.login;
  return (
    <div className={styles.wrap}>
      <h3>{title}</h3>
      {playerInfo ? (
        <div className={styles.info}>
          <div className={styles.avatar}>
            <img src={playerInfo.avatar_url} alt={name} />
            <span>{name}</span>
          </div>
          <div className={styles.ctl}>
            <button
              type="button"
              className="fa-stack fa-lg"
              onClick={onClearInput}
            >
              <i className="fa fa-circle fa-stack-2x text-danger" />
              <i className="fa fa-close fa-stack-1x fa-inverse" />
            </button>
          </div>
        </div>
      ) : (
        <Formik
          initialValues={{ loginname: "" }}
          validate={(values) => {
            const errors = {};
            if (!values.loginname) {
              errors.loginname = "Required";
            }
            return errors;
          }}
          onSubmit={(values, { setSubmitting, setFieldError }) => {
            onSubmitPlayer(values, (errMsg) => {
              setSubmitting(false);
              if (errMsg) setFieldError("loginname", errMsg);
            });
          }}
        >
          {({
            values,
            errors,
            handleChange,
            handleBlur,
            handleSubmit,
            isSubmitting,
            /* and other goodies */
          }) => (
            <form onSubmit={handleSubmit}>
              <input
                type="text"
                name="loginname"
                value={values.loginname}
                onChange={handleChange}
                onBlur={handleBlur}
                placeholder="github username"
              />
              <button type="submit" disabled={isSubmitting}>
                Submit
                {isSubmitting && <i className="fa fa-spinner fa-spin" />}
              </button>
              <div>{errors.loginname}</div>
            </form>
          )}
        </Formik>
      )}
    </div>
  );
}

export default PlayerInput;
